/**
 *
 *
 */
package com.fw.timesheet.controller.master;

import java.util.List;

import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Textbox;

import com.fw.timesheet.common.util.ServiceLocator;
import com.fw.timesheet.common.util.ZkUtils;
import com.fw.timesheet.controller.common.BaseController;
import com.fw.timesheet.model.Client;


/**
 * @author sigit <br>
 * @version 1.0 <br>
 * Application : timesheet <br>
 * Copyright (c) fastwire-group 2012 <br>
 * <br>
 */
public class ClientController extends BaseController {

	private Listbox clientListbox;
	private Textbox name;
	private Textbox country;
	private Client client;
	
	@Override
	public void doAfterCompose(Component aWindow) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(aWindow);
		loadAllClient();
	}
	
	private void loadAllClient() {
		List<Client> clients = ServiceLocator.getInstance().getClientService().findAll();
		clientListbox.getItems().clear();
		
		for (int i = 0 ; i < clients.size() ; i++) {
			client = clients.get(i);
			
			Listitem item = new Listitem();
			item.setValue(client);
			
			Listcell cell = new Listcell(client.getName());
			cell.setParent(item);
			
			cell = new Listcell(client.getCountry());
			cell.setParent(item);
			
			item.setParent(clientListbox);
		}
		client = null;
	}
	
	public void doSelect() {
		client = (Client) clientListbox.getSelectedItem().getValue() ;
		name.setValue(client.getName());
		country.setValue(client.getCountry());
		name.setFocus(true);
	}
	
	public void doEdit() {
		if (clientListbox.getSelectedItem() == null) {
			ZkUtils.showInfoMessage(Labels.getLabel("Common_Item_Not_Selected_Message"));
			return;
		}
		
		client = (Client) clientListbox.getSelectedItem().getValue() ;
		client.setName(name.getValue());
		client.setCountry(country.getValue());
		loadAllClient();
	}
	
	public void doSave() {
		if (client == null) {
			client = new Client();
			client.setName(name.getValue());
			client.setCountry(country.getValue());
			
		}
		ServiceLocator.getInstance().getClientService().saveAction(client);
		ZkUtils.showInfoMessage(Labels.getLabel("Common_Save_Successful_Message"));
		
		loadAllClient();
		
	}
	
    public void doDelete() {
    	if (clientListbox.getSelectedItem() == null) {
			ZkUtils.showInfoMessage(Labels.getLabel("Common_Item_Not_Selected_Message"));
			return;
		}
    	client = (Client) clientListbox.getSelectedItem().getValue();
		ServiceLocator.getInstance().getClientService().delete(client);
		ZkUtils.showInfoMessage(Labels.getLabel("Common_Delete_Success_Message"));
		loadAllClient();
	}
    
    public void doCancel() {
		name.setValue(null);
		country.setValue(null);
		client = null;
	}
	
}








